package com.github.llyb120.workflow.entity;

import com.github.llyb120.workflow.definition.Node;
import com.github.llyb120.workflow.definition.Startnode;
import com.github.llyb120.workflow.definition.Workflow;
import com.github.llyb120.workflow.domain.dos.UserDo;
import com.github.llyb120.workflow.excep.WorkflowException;

import java.util.List;
import java.util.stream.Collectors;

import static com.github.llyb120.workflow.WorkflowHolder.dealerAdapter;

public class WorkflowWrapper extends Workflow {

    private Workflow _wrapper;

    public WorkflowWrapper(Workflow workflow){
        this._wrapper = workflow;
    }

    @Override
    public List<Node> getNode() {
        return _wrapper.getNode();
    }

    @Override
    public void setNode(List<Node> value) {
        _wrapper.setNode(value);
    }

    @Override
    public String getId() {
        return _wrapper.getId();
    }

    @Override
    public void setId(String value) {
        _wrapper.setId(value);
    }

    /**
     * 获得node
     *
     * @param nodeId 节点ID
     * @return
     */
    public Node findNode(String nodeId){
        return getNode().stream().filter(e -> e.getId().equals(nodeId)).findFirst().orElseThrow(RuntimeException::new);
    }

    /**
     * 查询可执行人
     *
     * @param nodeId
     * @return
     */
    public List<UserDo> findDealers(String nodeId){
        Node node = findNode(nodeId);
        return dealerAdapter.findDealers(node.getDealer());
    }

    public List<Startnode> findStartNode(){
        List<Startnode> list = getNode()
                .stream()
                .filter(e -> e instanceof Startnode)
                .map(e -> (Startnode)e)
                .collect(Collectors.toList());
        if (list.isEmpty()) {
            throw new WorkflowException(WorkflowException.START_NODE_NOT_FOUND);
        }
        return list;
    }

}
